package utils

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"regexp"
	"strings"
	"time"
)

func ModificationData(data string) any {
	// 尝试直接解析为 JSON 数组
	var items []any
	if err := json.Unmarshal([]byte(data), &items); err == nil {
		return items
	}

	// 如果直接解析失败，尝试嵌套解析逻辑（兼容旧逻辑）
	var jsonString string
	if err := json.Unmarshal([]byte(data), &jsonString); err != nil {
		panic(fmt.Sprintf("解析外层JSON失败: %v", err))
	}

	// 然后，解析JSON字符串中的数组
	var rawItems []string
	if err := json.Unmarshal([]byte(jsonString), &rawItems); err != nil {
		panic(fmt.Sprintf("解析内层JSON数组失败: %v", err))
	}

	// 准备正则表达式来清理非标准JSON格式
	re := regexp.MustCompile(`(\w+):`)

	items = []any{}
	for _, raw := range rawItems {
		// 彻底清理字符串：移除所有空白字符（制表符、换行符、多余空格）
		cleaned := strings.TrimSpace(raw)
		cleaned = strings.ReplaceAll(cleaned, "\t", "")
		cleaned = strings.ReplaceAll(cleaned, "\n", "")
		cleaned = strings.ReplaceAll(cleaned, " ", "")   // 移除所有空格
		cleaned = strings.ReplaceAll(cleaned, ":", ": ") // 修复键值对格式
		cleaned = strings.ReplaceAll(cleaned, ",", ", ") // 修复逗号格式
		cleaned = strings.ReplaceAll(cleaned, "{", "{")  // 修复大括号格式
		cleaned = strings.ReplaceAll(cleaned, "}", "}")  // 修复大括号格式
		cleaned = strings.ReplaceAll(cleaned, "{", "{")  // 修复大括号格式
		cleaned = strings.ReplaceAll(cleaned, "}", "}")  // 修复大括号格式

		// 对于非标准JSON格式（属性名没有引号），添加引号
		if !strings.Contains(cleaned, `"id"`) {
			cleaned = re.ReplaceAllString(cleaned, `"$1":`)
		}

		// 修复 url 字段的多余引号
		cleaned = strings.ReplaceAll(cleaned, `""https"`, `"https`)

		// 解析为Item对象
		var item any
		if err := json.Unmarshal([]byte(cleaned), &item); err != nil {
			panic(fmt.Sprintf("解析项目失败: %v\n原始数据: %s\n处理后: %s", err, raw, cleaned))
		}

		items = append(items, item)
	}

	return items
}

func generateTemplate(filePath, key string, expires int64) string {
	return fmt.Sprintf("%s-%d-0-0-%s", filePath, expires, key)
}

func generateMD5Hash(signStr string) (string, error) {
	hasher := md5.New()

	_, err := hasher.Write([]byte(signStr))
	if err != nil {
		return "", fmt.Errorf("计算 MD5 哈希时出错: %v", err)
	}

	hashBytes := hasher.Sum(nil)
	hashString := hex.EncodeToString(hashBytes)

	return hashString, nil
}

func AddGenerateSignedUrl(filePath string) string {
	key := "xue202508162301"
	expirationTime := int64(1800)
	expires := time.Now().Unix() + expirationTime
	signStr := generateTemplate(filePath, key, expires)
	signature, err := generateMD5Hash(signStr)
	if err != nil {
		fmt.Printf("错误: %v\n", err)
		return ""
	}
	signedUrl := fmt.Sprintf("https://www.zuoyuan.asia%s?auth_key=%d-0-0-%s", filePath, expires, signature)
	return signedUrl
}
